/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tarearonald;

import java.sql.Connection;
import java.sql.SQLException;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Oscar Eduardo
 */
public class InterVentas extends javax.swing.JInternalFrame implements InternalFrameListener {

    /**
     * Creates new form InterVentas
     */
    JMenuItem ref;

    public InterVentas(JMenuItem ref) throws SQLException {
        this.ref = ref;
        ref.setEnabled(false);
        this.addInternalFrameListener(this);
        setClosable(true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);
        initComponents();
        llenarCombo();

    }

    public void llenarCombo() throws SQLException {
        Conex obj = new Conex();
        Connection con = obj.conectar();
        String query = "select nombre from productos";
        String result[][];
        result = obj.select(con, query);
        String arr[] = new String[result.length];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = result[i][0];
        }
        jComboBoxProducto.setModel(new javax.swing.DefaultComboBoxModel(arr));
        jComboBoxProducto.setSelectedIndex(-1);
        con.close();


    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jComboBoxProducto = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jtxtCantidad = new javax.swing.JTextField();
        jButtonAgregar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableVenta = new javax.swing.JTable();
        jButtonVenta = new javax.swing.JButton();

        jLabel1.setText("Producto");

        jLabel2.setText("Cantidad");

        jButtonAgregar.setText("Agregar");
        jButtonAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAgregarActionPerformed(evt);
            }
        });

        jTableVenta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Producto", "Cantidad", "Total"
            }
        ));
        jScrollPane1.setViewportView(jTableVenta);
        jTableVenta.getColumnModel().getColumn(0).setResizable(false);
        jTableVenta.getColumnModel().getColumn(1).setResizable(false);

        jButtonVenta.setText("Realizar venta");
        jButtonVenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonVentaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButtonVenta)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButtonAgregar)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addGap(42, 42, 42)
                            .addComponent(jComboBoxProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(39, 39, 39)
                            .addComponent(jLabel2)
                            .addGap(18, 18, 18)
                            .addComponent(jtxtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 461, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jtxtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jButtonAgregar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButtonVenta)
                .addContainerGap(38, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAgregarActionPerformed
        // TODO add your handling code here:
        if (jtxtCantidad.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Ingrese los datos");
        } else {
            Conex obj = new Conex();
            Connection con = obj.conectar();
            String query = "select precio from Productos where nombre = '" + jComboBoxProducto.getSelectedItem().toString() + "'";
            String result[][];
            result = obj.select(con, query);
            float precio = Float.parseFloat(result[0][0]);
            DefaultTableModel temp = (DefaultTableModel) jTableVenta.getModel();
            JTable jTable1 = new JTable(temp);
            Object[] fila = new Object[3];
            fila[0] = jComboBoxProducto.getSelectedItem().toString();
            fila[1] = jtxtCantidad.getText();
            fila[2] = precio * (Integer.parseInt(jtxtCantidad.getText()));
            temp.addRow(fila);
            jComboBoxProducto.setSelectedIndex(-1);
            jtxtCantidad.setText("");
            obj.close(con);

        }
    }//GEN-LAST:event_jButtonAgregarActionPerformed

    private void jButtonVentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonVentaActionPerformed
        // TODO add your handling code here:
        if (jTableVenta.getRowCount() > 0) {
            Conex obj = new Conex();
            Connection con = obj.conectar();
            String query;
            float subTotal = 0.0f;
            float iva = 0.0f;
            float total = 0.0f;
            for (int j = 0; j < jTableVenta.getRowCount(); j++) {
                subTotal += Float.parseFloat(jTableVenta.getValueAt(j, 2).toString());
            }
            iva = subTotal * 0.16f;
            total = subTotal + iva;
            query = "insert into ventas values('" + subTotal + "', '" + iva + "', '" + total + "')";
            System.out.println("" + query);
            obj.insertar(con, query);

            query = "select max(id) from ventas";
            String result[][];
            result = obj.select(con, query);
            int idVenta = Integer.parseInt(result[0][0]);
            for (int j = 0; j < jTableVenta.getRowCount(); j++) {
                query = "select id from productos where nombre = '"+jTableVenta.getValueAt(j, 0)+"'";
                result = obj.select(con, query);
                query = "insert into detventa values(" + idVenta + ", '"
                        +result[0][0]+"', '"+jTableVenta.getValueAt(j, 1)+"', "
                        + ""+jTableVenta.getValueAt(j, 2)+")";
                System.out.println(""+query);
                obj.insertar(con, query);
            }
            JOptionPane.showMessageDialog(null, "venta realizada");
            obj.close(con);
        }


    }//GEN-LAST:event_jButtonVentaActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAgregar;
    private javax.swing.JButton jButtonVenta;
    private javax.swing.JComboBox jComboBoxProducto;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableVenta;
    private javax.swing.JTextField jtxtCantidad;
    // End of variables declaration//GEN-END:variables

    @Override
    public void internalFrameOpened(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameClosing(InternalFrameEvent e) {
        this.ref.setEnabled(true);
    }

    @Override
    public void internalFrameClosed(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameIconified(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameDeiconified(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameActivated(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameDeactivated(InternalFrameEvent e) {
    }
}
